package com.airS.task.fileMgr.service.mgr.impl;

import com.airS.task.fileMgr.model.mgr.FileInfo;
import com.airS.task.fileMgr.service.mgr.FdfsService;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * fastdfs服务
 * Created by alan on 2017/3/18.
 */
@Service
public class FdfsServiceImpl implements FdfsService, InitializingBean{

    private static final Logger logger = LoggerFactory.getLogger(FdfsServiceImpl.class);

    @Value("${fdfs.client.config}")
    private String clientConfig;

    private TrackerClient trackerClient;

    private StorageServer storageServer;

    @Override
    public String uploadToFastDFS(FileInfo fileInfo) throws IOException {

        TrackerServer trackerServer = trackerClient.getConnection();

        StorageClient storageClient = new StorageClient(trackerServer, storageServer);

        double fileLength = fileInfo.getContent().length;

        logger.info("upload file name:{},  file length:{}M", fileInfo.getName(), fileLength / (1024*1024));

        NameValuePair[] meta_list = buildNameValuePairs(fileInfo);
        String[] uploadResults = null;
        try {
            uploadResults = storageClient.upload_file(fileInfo.getContent(), fileInfo.getExt(), meta_list);
        } catch (Exception e) {
            throw new RuntimeException("fdfs上传异常", e);
        }
        if (uploadResults == null) {
            throw new RuntimeException("fdfs上传异常, errorCode: " + String.valueOf(storageClient.getErrorCode()));
        }

        String groupName = uploadResults[0];
        String remoteFileName = uploadResults[1];

        String filePath = groupName + "/" + remoteFileName;

        return filePath;
    }

    private NameValuePair[] buildNameValuePairs(FileInfo file) {
        NameValuePair[] meta_list = new NameValuePair[6];
        meta_list[0] = new NameValuePair("name", file.getName());
        meta_list[1] = new NameValuePair("ext", file.getExt());
        meta_list[2] = new NameValuePair("length", String.valueOf(file.getContent().length));
        meta_list[3] = new NameValuePair("width", file.getWidth());
        meta_list[4] = new NameValuePair("heigth", file.getHeight());
        meta_list[5] = new NameValuePair("author", file.getAuthor());
        return meta_list;
    }

    @Override
    public Map<String, String> getMetaFromFastDFS(String groupName, String fileName) throws IOException {
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);
        NameValuePair[] metadata = new NameValuePair[0];
        try {
            metadata = storageClient.get_metadata(groupName, fileName);
            Map<String, String> fileMeta = new HashMap<>();
            for (NameValuePair pair : metadata) {
                fileMeta.put(pair.getName(), pair.getValue());
            }
            return fileMeta;
        } catch (Exception e) {
            throw new RuntimeException("fdfs获取元信息异常, errorCode: " + String.valueOf(storageClient.getErrorCode()));
        }
    }

    @Override
    public void deleteFromFastDFS(String groupName, String fileName) throws IOException {
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);
        try {
            storageClient.delete_file(groupName, fileName);
            logger.info("delete file groupName:{},  fileName:{}", groupName, fileName);
        } catch (Exception e) {
            throw new RuntimeException("fdfs删除文件异常, errorCode: " + String.valueOf(storageClient.getErrorCode()));
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ClassPathResource fdfsConf = new ClassPathResource(clientConfig);
//        ClientGlobal.init(clientConfig, fdfsConf.getInputStream());
        logger.info("FastDFS configuration file path: " + fdfsConf.getFile().getPath());
//        String configPath = this.getClass().getResource("/").getPath() + clientConfig;
        ClientGlobal.init(fdfsConf.getFile().getPath());

        trackerClient = new TrackerClient();
    }

}
